<template>
    <div>
        <div>
            <el-dialog title="添加部门" :visible.sync="dialogFormVisible">
                <el-form ref="elForm" :model="model" :rules="rules" size="medium" label-width="100px">
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="model.name" placeholder="请输入部门名称" clearable :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="model.status" placeholder="请选择状态" :style="{ width: '100%', height: '100%' }">
                            <el-option style="height: 50%" value="0" label="停用"></el-option>
                            <el-option style="height: 50%" value="1" label="正常"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上级机构" prop="superiorId">
                        <el-select v-model="kk" placeholder="请选择上级部门" :style="{ width: '100%', height: '100%' }">
                            <el-option style="height: 50%" value="0" label="根节点">根节点</el-option>
                            <el-option style="height: 50%" value="">
                                <el-tree
                                    :data="DepartmentIdTreeData"
                                    :props="defaultProps"
                                    :node-key="depId"
                                    default-expand-all
                                    :expand-on-click-node="false"
                                    @node-click="Shs"
                                >
                                </el-tree>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm">提交</el-button>
                </div>
            </el-dialog>
            <el-dialog title="修改部门" :visible.sync="dialogFormVisibles">
                <el-form ref="elForms" :model="models" :rules="rulees" size="medium" label-width="100px">
                    <el-form-item label="Id" prop="depId">
                        <span>{{ models.depId }}</span>
                    </el-form-item>
                    <el-form-item label="层级Id" prop="name">
                        <span>{{ models.cascadeId }}</span>
                    </el-form-item>
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="models.name" placeholder="请输入部门名称" clearable :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="models.status" placeholder="请选择状态" :style="{ width: '100%', height: '100%' }">
                            <el-option style="height: 50%" value="0" label="停用"></el-option>
                            <el-option style="height: 50%" value="1" label="正常"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上级ID" prop="superiorId">
                        <el-select v-model="kks" placeholder="请选择上级部门" :style="{ width: '100%', height: '100%' }">
                            <el-option style="height: 50%" value="0" label="根节点"></el-option>
                            <el-option style="height: 50%" value="">
                                <el-tree
                                    :data="DepartmentIdTreeData"
                                    :props="defaultProps"
                                    :node-key="depId"
                                    default-expand-all
                                    :expand-on-click-node="false"
                                    @node-click="Shes"
                                >
                                </el-tree>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibles = false">取 消</el-button>
                    <el-button type="primary" @click="submitForms">提交</el-button>
                </div>
            </el-dialog>
            <el-dialog title="部门用户" :visible.sync="departmentsUserdialog" @closed="Back">
                <el-table
                    ref="multipleUser"
                    :data="tableDataUser"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSelectionChanges"
                >
                    <el-table-column type="selection" width="55"> </el-table-column>
                    <el-table-column label="用户ID" width="120">
                        <template slot-scope="scope">{{ scope.row.uId }}</template>
                    </el-table-column>
                    <el-table-column prop="account" label="用户账号名" width="120"> </el-table-column>
                    <el-table-column prop="uName" label="用户名" width="120"> </el-table-column>
                    <el-table-column label="状态" width="180">
                        <template slot-scope="scope">{{ scope.row.status ? '正常' : '离线' }}</template>
                    </el-table-column>
                </el-table>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="Back()">取 消</el-button>
                    <el-button type="primary" @click="AddDepartmentsUser()">确 定</el-button>
                </div>
            </el-dialog>
        </div>
        <el-container>
            <el-header>
                <div style="float: right">
                    <div style="float: left">
                        <el-input v-model="names" placeholder="请输入部门名称" style="float: left"></el-input>
                    </div>
                    &nbsp; &nbsp;
                    <el-button type="primary" @click="Shows()">查询</el-button>
                    <el-button type="success" @click="dialogFormVisible = true">添加</el-button>
                    <el-button type="warning" @click="OpenDepartmentsUser()">分配用户</el-button>
                    <el-button @click="handleClick()" type="danger" size="small">删除</el-button>
                </div>
            </el-header>
            <el-container>
                <el-aside width="200px">
                    <el-button type="text" style="font-size: 20px" @click="Ret()">全部显示>>></el-button>
                    <el-tree :data="data" 
                    :props="defaultProps" 
                    default-expand-all 
                    :expand-on-click-node="false" 
                    @node-click="Sh">
                </el-tree>
            </el-aside>
                <el-main
                    ><el-table
                        ref="multipleUser"
                        :data="tableData"
                        border
                        tooltip-effect="dark"
                        style="width: 100%"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column type="selection" width="55"> </el-table-column>
                        <el-table-column prop="cascadeId" label="层级Id"> </el-table-column>
                        <el-table-column prop="name" label="部门名称"> </el-table-column>
                        <el-table-column prop="account" label="用户"> </el-table-column>
                        <el-table-column prop="pName" label="上级部门"> </el-table-column>
                        <el-table-column label="状态" width="180">
                            <template slot-scope="scope">
                                <span v-if="scope.row.status == 1" style="color: green"> 正常 </span>
                                <span v-else style="color: red"> 停用 </span>
                            </template>
                        </el-table-column>

                        <el-table-column fixed="right" label="操作">
                            <template slot-scope="scope">
                                <el-button @click="Ut(scope.row)" type="primary" size="small">编辑</el-button>

                                <el-button v-show="scope.row.status == 1" @click="Upt(scope.row.depId)" type="danger" size="small"
                                    >停用</el-button
                                >
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="Pindex"
                            :page-sizes="[10, 20, 30, 40]"
                            :page-size="Psize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="DCount"
                        >
                        </el-pagination></div
                ></el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script>
import {
    DeparTreeShow,
    DeparAdd,
    DeparShows,
    DeparDel,
    DeparUpt,
    DepartmentsUser,
    BackDepartment,
    DeparUpdate,
    Deparback
} from '@/api/departments';

import { getUsers } from '@/api/user';
export default {
    data() {
        return {
            data: [],
            tableData: [],
            defaultProps: {
                children: 'dlist',
                label: 'name',
                value: 'depId'
            },
            DepartmentIdTreeData: [],
            query: {
                name: undefined,
                pageIndex: 1,
                pageSize: 10
            },
            Pindex: 1,
            Psize: 10,
            DCount: 0,
            did: [],
            names: '',
            ids: [],
            dialogFormVisible: false,
            dialogFormVisibles: false,
            model: {
                name: undefined,
                parentId: 0,
                status: ''
            },
            models: {
                depId: undefined,
                name: undefined,
                parentId: undefined,
                cascadeId: undefined,
                status: undefined
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: '请输入部门名称',
                        trigger: 'blur'
                    }
                ],
                parentId: [
                    {
                        required: true,
                        message: '请输入上级ID',
                        trigger: 'blur'
                    }
                ]
            },
            rulees: {
                name: [
                    {
                        required: true,
                        message: '请输入部门名称',
                        trigger: 'blur'
                    }
                ],
                parentId: [
                    {
                        required: true,
                        message: '请输入上级ID',
                        trigger: 'blur'
                    }
                ]
            },
            multipleSelection: [],
            multipleUser: [],
            tableDataUser: [],
            departmentsUserdialog: false,
            depId: undefined,
            uId: [],
            kk: '根节点',
            kks: undefined
        };
    },
    mounted() {
        this.CallInOrder();
    },
    methods: {
        //加载左侧菜单树
        async ShowTree() {
            await DeparTreeShow().then((d) => {
                this.data = d.data;
                this.DepartmentIdTreeData = d.data;
            });
        },
        //加载部门列表
        async Shows() {
            await DeparShows(this.Pindex, this.Psize, this.did, this.names).then((d) => {
                this.tableData = d.data.pageList;
                this.DCount = d.data.totalCount;
                console.log(this.tableData);
            });
        },
        async CallInOrder() {
            await this.ShowTree();
            this.Shows(); //加载右侧部门表
            await this.ShowUsers();
        },
        async UptShow() {
            await this.ShowTree();
            await this.Shows();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
            this.ids = this.multipleSelection.map((x) => x.depId);
            console.log(this.ids);
        },
        handleSelectionChanges(val) {
            this.multipleUser = val;
        },
        Sh(row) {
            console.log(row);
            this.did = row.cascadeId;
            console.log(this.did);
            this.Shows();
        },
        Shs(row) {
            console.log(row.depId);
            this.model.parentId = row.depId;

            this.kk = row.name;
        },
        Shes(row) {
            this.models.parentId = row.depId;

            this.kks = row.name;
        },
        Uts() {
            if (this.multipleSelection.length == 0 || this.multipleSelection.length > 1) {
                this.$message({
                    message: '请选择一个部门',
                    type: 'warning'
                });
                return;
            } else {
                this.models.depId = this.multipleSelection.map((x) => x.depId).toString();
                this.dialogFormVisibles = true;
                Deparback(row.depId).then((d) => {
                    this.models = d.data;
                    this.kks = this.models.pName;
                });
            }
        },
        Uttt() {
            if (this.multipleSelection.length == 0 || this.multipleSelection.length > 1) {
                this.$message({
                    message: '请选择一个部门',
                    type: 'warning'
                });
                return;
            } else {
                var row = this.multipleSelection[0];
                console.log(row);
                this.models.depId = row.depId;
                this.models.name = row.name;
                this.models.parentId = row.parentId;
                this.kks = row.pName;
                this.models.cascadeId = row.cascadeId;
                this.models.status = row.status;
                this.dialogFormVisibles = true;
                console.log(this.models);
            }
        },
        Ut(row) {
            console.log(row);
            this.models.depId = row.depId;
            this.models.name = row.name;
            this.models.parentId = row.parentId;
            this.kks = row.pName;
            this.models.cascadeId = row.cascadeId;
            this.models.status = row.status.toString();
            console.log(this.models);
            this.dialogFormVisibles = true;
            console.log(this.models);
        },
        
        handleClick() {
            if (this.multipleSelection.length == 0) {
                this.$message({
                    message: '请选择一个部门',
                    type: 'warning'
                });
                return;
            } else {
                this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    DeparDel(this.multipleSelection.map((x) => x.depId).toString()).then((d) => {
                        if (d.data > 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.Shows();
                        } else {
                            this.$message({
                                type: 'info',
                                message: '删除失败'
                            });
                        }
                    });
                });
            }
        },
        submitForm() {
            this.$refs['elForm'].validate((valid) => {
                if (valid) {
                    this.Add();
                } else {
                    return false;
                }
                // TODO 提交表单
            });
        },
        Add() {
            DeparAdd(this.model).then((d) => {
                if (d.code > 0) {
                    this.$message({
                        message: '部门添加成功',
                        type: 'success'
                    });
                    this.model = {};
                    this.dialogFormVisible = false;
                    this.UptShow();
                } else {
                    this.$message({
                        message: '部门添加失败',
                        type: 'warning'
                    });
                    this.model = {};
                    this.dialogFormVisible = false;
                }
            });
        },
        submitForms() {
            this.$refs['elForms'].validate((valid) => {
                if (valid) {
                    this.Update();
                } else {
                    return false;
                }
                // TODO 提交表单
            });
        },
        Update() {
            DeparUpdate(this.models).then((d) => {
                if (d.code > 0) {
                    this.$message({
                        message: '部门修改成功',
                        type: 'success'
                    });

                    this.dialogFormVisibles = false;
                    this.UptShow();
                } else {
                    this.$message({
                        message: '部门修改失败',
                        type: 'warning'
                    });

                    this.dialogFormVisibles = false;
                }
            });
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.Psize = val;
            this.Shows();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.Pindex = val;
            this.Shows();
        },
        Ret() {
            this.did = 0;
            this.Shows();
        },
        Upt(row) {
            DeparUpt(row).then((d) => {
                if (d.data > 0) {
                    this.$message({
                        type: 'success',
                        message: '停用成功!'
                    });
                    this.Shows();
                } else {
                    this.$message({
                        type: 'info',
                        message: '停用失败'
                    });
                }
            });
        },
        //打开用户关系的添加
        OpenDepartmentsUser() {
            if (this.multipleSelection === undefined || this.multipleSelection.length === 0 || this.multipleSelection.length > 1) {
                this.$message({
                    message: '请选择一个部门',
                    type: 'warning'
                });
                return;
            } else {
                this.departmentsUserdialog = true;
                this.depId = this.multipleSelection.map((x) => x.depId).toString();
                BackDepartment(this.depId).then((d) => {
                    console.log(d.data.pageList.map((x) => x.uId));
                    this.tableDataUser.forEach((row) => {
                        for (let j in d.data.pageList) {
                            if (row.uId == d.data.pageList[j].uId) {
                                this.$refs.multipleUser.toggleRowSelection(row, true);
                                break;
                            }
                        }
                    });
                });
            }
        },
        Back() {
            this.departmentsUserdialog = false;
            this.$refs.multipleUser.clearSelection();
        },
        //显示角色
        async ShowUsers() {
            await getUsers(this.query).then((res) => {
                console.log('用户列表:', res);
                this.tableDataUser = res.data.list;
            });
        },
        //添加用户角色关系
        AddDepartmentsUser() {
            this.uId = this.multipleUser.map((x) => x.uId).toString();
            DepartmentsUser(this.depId, this.uId).then((d) => {
                if (d.data > 0) {
                    this.$message({
                        message: '部门用户关系添加成功',
                        type: 'success'
                    });
                    this.departmentsUserdialog = false;
                    this.Shows();
                } else {
                    this.$message({
                        message: '部门用户关系添加失败',
                        type: 'warning'
                    });
                }
            });
        }
    }
};
</script>
 
